package com.rickpan.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.rickpan.entity.PaymentOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付集成服务
 */
@Service
@Slf4j
public class AlipayService {

    @Value("${alipay.app-id}")
    private String appId;

    @Value("${alipay.gateway-url}")
    private String gatewayUrl;

    @Value("${alipay.merchant-private-key}")
    private String merchantPrivateKey;

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    @Value("${alipay.return-url}")
    private String returnUrl;

    @Value("${alipay.sign-type}")
    private String signType;

    @Value("${alipay.charset}")
    private String charset;

    private AlipayClient alipayClient;

    @PostConstruct
    public void init() {
        this.alipayClient = new DefaultAlipayClient(
            gatewayUrl,
            appId,
            merchantPrivateKey,
            "json",
            charset,
            alipayPublicKey,
            signType
        );
        log.info("支付宝客户端初始化完成");
    }

    /**
     * 创建支付宝支付链接 (临时模拟版本)
     */
    public String createPayment(PaymentOrder order) {
        log.warn("使用模拟支付接口 - 支付宝签名问题待修复");
        
        // 生成模拟的支付页面HTML
        String mockPaymentHtml = generateMockPaymentHtml(order);
        
        log.info("生成模拟支付页面: orderNo={}", order.getOrderNo());
        return mockPaymentHtml;
    }
    
    /**
     * 生成模拟支付页面HTML
     */
    private String generateMockPaymentHtml(PaymentOrder order) {
        String orderNo = order.getOrderNo();
        String planName = getPlanSubject(order.getPlanType());
        String amount = String.format("%.2f", order.getAmount());
        
        return "<!DOCTYPE html>\n" +
            "<html>\n" +
            "<head>\n" +
            "    <title>RickPan VIP 模拟支付</title>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
            "    <style>\n" +
            "        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 40px; text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; }\n" +
            "        .container { background: white; padding: 40px; border-radius: 16px; max-width: 450px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); }\n" +
            "        .title { color: #409eff; font-size: 28px; margin-bottom: 10px; font-weight: 600; }\n" +
            "        .subtitle { color: #909399; font-size: 14px; margin-bottom: 30px; }\n" +
            "        .info { margin: 15px 0; color: #606266; font-size: 16px; }\n" +
            "        .label { color: #909399; font-size: 14px; }\n" +
            "        .value { color: #303133; font-weight: 500; }\n" +
            "        .amount { font-size: 36px; color: #f39c12; font-weight: bold; margin: 30px 0; }\n" +
            "        .btn { background: #409eff; color: white; border: none; padding: 15px 30px; \n" +
            "               border-radius: 8px; font-size: 16px; cursor: pointer; margin: 10px; min-width: 140px; transition: all 0.3s; }\n" +
            "        .btn:hover { background: #337ecc; transform: translateY(-1px); }\n" +
            "        .btn.cancel { background: #909399; }\n" +
            "        .btn.cancel:hover { background: #767a82; }\n" +
            "        .warning { background: #fff3cd; color: #856404; padding: 15px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #f39c12; }\n" +
            "        .buttons { margin-top: 30px; }\n" +
            "    </style>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <div class=\"container\">\n" +
            "        <div class=\"title\">RickPan VIP</div>\n" +
            "        <div class=\"subtitle\">模拟支付页面</div>\n" +
            "        <div class=\"warning\">\n" +
            "            <strong>⚠️ 开发测试模式</strong><br>\n" +
            "            这是临时的模拟支付，支付宝集成问题修复中\n" +
            "        </div>\n" +
            "        <div class=\"info\">\n" +
            "            <div class=\"label\">订单号</div>\n" +
            "            <div class=\"value\">" + orderNo + "</div>\n" +
            "        </div>\n" +
            "        <div class=\"info\">\n" +
            "            <div class=\"label\">套餐类型</div>\n" +
            "            <div class=\"value\">" + planName + "</div>\n" +
            "        </div>\n" +
            "        <div class=\"amount\">¥ " + amount + "</div>\n" +
            "        <div class=\"buttons\">\n" +
            "            <button class=\"btn\" onclick=\"simulateSuccess()\">✅ 模拟支付成功</button><br>\n" +
            "            <button class=\"btn cancel\" onclick=\"simulateCancel()\">❌ 取消支付</button>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "    \n" +
            "    <script>\n" +
            "        function simulateSuccess() {\n" +
            "            const btn = event.target;\n" +
            "            btn.disabled = true;\n" +
            "            btn.innerHTML = '⏳ 处理中...';\n" +
            "            \n" +
            "            const params = new URLSearchParams({\n" +
            "                out_trade_no: '" + orderNo + "',\n" +
            "                trade_no: 'MOCK_' + Date.now(),\n" +
            "                trade_status: 'TRADE_SUCCESS',\n" +
            "                total_amount: '" + amount + "'\n" +
            "            });\n" +
            "            \n" +
            "            // 延迟1秒模拟网络请求\n" +
            "            setTimeout(() => {\n" +
            "                window.location.href = 'http://localhost:8080/api/payment/mock/return?' + params.toString();\n" +
            "            }, 1000);\n" +
            "        }\n" +
            "        \n" +
            "        function simulateCancel() {\n" +
            "            const params = new URLSearchParams({\n" +
            "                success: 'false',\n" +
            "                message: '用户取消支付'\n" +
            "            });\n" +
            "            window.location.href = 'http://localhost:5173/pay-result?' + params.toString();\n" +
            "        }\n" +
            "    </script>\n" +
            "</body>\n" +
            "</html>";
    }

    /**
     * 验证支付宝回调签名
     */
    public boolean verifyCallback(Map<String, String> params) {
        try {
            // 移除sign和sign_type参数
            Map<String, String> verifyParams = new HashMap<>(params);
            verifyParams.remove("sign");
            verifyParams.remove("sign_type");

            // 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                verifyParams,
                alipayPublicKey,
                charset,
                signType
            );

            log.info("支付宝回调签名验证结果: {}, orderNo: {}", 
                    signVerified, params.get("out_trade_no"));

            return signVerified;

        } catch (AlipayApiException e) {
            log.error("支付宝回调签名验证失败", e);
            return false;
        }
    }

    /**
     * 处理支付宝同步回调
     */
    public Map<String, String> handleSyncCallback(Map<String, String> params) {
        Map<String, String> result = new HashMap<>();
        
        try {
            if (!verifyCallback(params)) {
                result.put("success", "false");
                result.put("message", "签名验证失败");
                return result;
            }

            String tradeStatus = params.get("trade_status");
            String orderNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");

            log.info("处理支付宝同步回调: orderNo={}, tradeStatus={}", orderNo, tradeStatus);

            result.put("success", "true");
            result.put("orderNo", orderNo);
            result.put("tradeNo", tradeNo);
            result.put("tradeStatus", tradeStatus);

        } catch (Exception e) {
            log.error("处理支付宝同步回调失败", e);
            result.put("success", "false");
            result.put("message", "处理回调失败");
        }

        return result;
    }

    /**
     * 处理支付宝异步通知
     */
    public boolean handleAsyncNotify(Map<String, String> params) {
        try {
            if (!verifyCallback(params)) {
                log.error("支付宝异步通知签名验证失败");
                return false;
            }

            String tradeStatus = params.get("trade_status");
            String orderNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");

            log.info("处理支付宝异步通知: orderNo={}, tradeStatus={}", orderNo, tradeStatus);

            // 只处理支付成功的通知
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                // 这里应该调用PaymentService来处理支付成功逻辑
                // 但为了避免循环依赖，由Controller调用
                return true;
            }

            return false;

        } catch (Exception e) {
            log.error("处理支付宝异步通知失败", e);
            return false;
        }
    }

    /**
     * 获取套餐标题
     */
    private String getPlanSubject(PaymentOrder.PlanType planType) {
        return switch (planType) {
            case MONTHLY_VIP -> "VIP Monthly";
            case YEARLY_VIP -> "VIP Yearly";
        };
    }

    /**
     * 获取套餐描述
     */
    private String getPlanDescription(PaymentOrder.PlanType planType) {
        return switch (planType) {
            case MONTHLY_VIP -> "VIP Monthly Plan";
            case YEARLY_VIP -> "VIP Yearly Plan";
        };
    }

    /**
     * 获取异步通知地址
     */
    private String getNotifyUrl() {
        // 这里应该返回您的服务器异步通知接收地址
        // 例如: https://your-domain.com/api/vip/callback/payment
        return "http://localhost:8080/api/vip/callback/payment";
    }

    /**
     * 获取支付宝配置信息 (用于前端)
     */
    public Map<String, String> getAlipayConfig() {
        Map<String, String> config = new HashMap<>();
        config.put("appId", appId);
        config.put("gatewayUrl", gatewayUrl);
        config.put("returnUrl", returnUrl);
        config.put("signType", signType);
        config.put("charset", charset);
        return config;
    }
}